#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../test_helper'

require 'test/unit'
require 'container/site_controller'

class SiteControllerTest < Test::Unit::TestCase

  include FileUtils

  def setup
    @sandbox = Sandbox.new

    SiteController.expects(:valid_domain?).with('foo.com').returns(true)
    mkdir_p "#{@sandbox.root}/foo.com"
    @mongrel_controller = MongrelController.new("#{@sandbox.root}/foo.com")
    MongrelController.stubs(:for_domain).returns(@mongrel_controller)

    @site_controller = SiteController.new('foo.com')

    # do not _really_ execute any shell commands
    @mongrel_controller.stubs(:execute)
    @mongrel_controller.stubs(:execute)
    @mongrel_controller.stubs(:chown)
    @site_controller.stubs(:execute)
  end

  def teardown
    @sandbox.clean_up
  end

  def test_invoke
    @mongrel_controller.create_container(['host1', 'host2'], 4000..4001)

    assert_equal %w( monit.host1.4000.config monit.host1.4001.config.reserve monit.host2.4000.config monit.host2.4001.config.reserve ),
                 config_files

    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host1.config stop foo.com_host1_4000")
    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host2.config stop foo.com_host2_4000")
    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host1.config reload")
    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host2.config reload")

    @site_controller.stop

    assert_equal %w( monit.host1.4000.config.stopped monit.host1.4001.config.reserve monit.host2.4000.config.stopped monit.host2.4001.config.reserve ),
                 config_files

    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host1.config start foo.com_host1_4000")
    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host2.config start foo.com_host2_4000")
    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host1.config reload")
    @site_controller.expects(:execute).with("monit -c #{server_config_dir}/monit.host2.config reload")

    @site_controller.start

    assert_equal %w( monit.host1.4000.config monit.host1.4001.config.reserve monit.host2.4000.config monit.host2.4001.config.reserve ),
                 config_files
  end

  def config_files
    Dir["#{@mongrel_controller.config_dir}/monit.*"].map { |path| File.basename(path) }.sort
  end

  def server_config_dir
    File.join(ROR_SERVICE_ROOT, 'config')
  end
  

end

